package com.gzhryc.net_marketing.cloud.goods.services;

import com.gzhryc.common.StringTools;
import com.gzhryc.common.api.DefaultAPICodeConstants;
import com.gzhryc.common.api.DefaultAPIResponse;
import com.gzhryc.common.exceptions.LogicException;
import com.gzhryc.common.logging.Logger;
import com.gzhryc.jdbc.Conditions;
import com.gzhryc.jdbc.JdbcSession;
import com.gzhryc.jdbc.MultiDBTools;
import com.gzhryc.net_marketing.cloud.notice.SupplyChainNoticeService;
import com.gzhryc.net_marketing.core.notice.goods.GoodsAuditResultNotice;
import com.gzhryc.net_marketing.cloud.MarketConstants;
import com.gzhryc.net_marketing.cloud.goods.dao.CloudGoodsAuditApplyDao;
import com.gzhryc.net_marketing.cloud.goods.dao.db.CloudGoods;
import com.gzhryc.net_marketing.cloud.goods.dao.db.CloudGoodsAuditApply;
import com.gzhryc.net_marketing.cloud.goods.dao.db.CloudGoodsSpaceAuditItem;
import com.gzhryc.net_marketing.cloud.goods.services.dto.CloudGoodsAuditApplySearch;
import com.gzhryc.net_marketing.core.enums.EGoodsAuditState;

import java.sql.SQLException;
import java.util.Date;
import java.util.List;

public class CloudGoodsAuditApplyService {

    static Logger log = Logger.getLogger(CloudGoodsAuditApplyService.class);

    public static CloudGoodsAuditApplyService self() {
        return MultiDBTools.getService(MarketConstants.JDBC_KEY,CloudGoodsAuditApplyService.class, true);
    }

    CloudGoodsAuditApplyDao dao;

    public CloudGoodsAuditApplyService(String jdbcKey) {
        this.dao = new CloudGoodsAuditApplyDao(jdbcKey);
    }

    public List<CloudGoodsAuditApply> findJoinBySearch(CloudGoodsAuditApplySearch search, Integer pageNo, Integer pageLimit){
        Conditions condition = dao.buildConditions(search);
        condition.desc("createDate");

        try {
            return dao.findJoinByCondition(condition);
        } catch (SQLException e) {
            log.error(e.getMessage(),e);
        }
        return null;
    }

    public Long countJoinBySearch(CloudGoodsAuditApplySearch search){
        Conditions condition = dao.buildConditions(search);
        try {
            return dao.countJoin(condition);
        } catch (SQLException e) {
            log.error(e.getMessage(),e);
        }
        return 0L;
    }

    public List<CloudGoodsAuditApply> findAuditGoodsRecordBySupplierIdAndGoodsId(Long supplierId, Long goodsId){
        if(supplierId != null && goodsId != null){
            Conditions condition = new Conditions(CloudGoodsAuditApply.class);
            condition.and().is("supplierId",supplierId);
            condition.and().is("goodsId",goodsId);

            try {
                return dao.findByCondition(condition);
            } catch (SQLException e) {
                log.error(e.getMessage(),e);
            }
        }
        return null;
    }

    public CloudGoodsAuditApply getById(Long id){
        if(id != null) {
            try {
                return dao.getById(id);
            } catch (SQLException e) {
                log.error(e.getMessage(),e);
            }
        }
        return null;
    }

    public CloudGoodsAuditApply getJoinById(Long id){
        if(id != null) {
            try {
                return dao.getJoinById(id);
            } catch (SQLException e) {
                log.error(e.getMessage(),e);
            }
        }
        return null;
    }

    public CloudGoodsAuditApply getByIdGoodsCode(String goodsCode) {
        if (StringTools.isNotBlank(goodsCode)) {
            Conditions conditions = new Conditions(CloudGoodsAuditApply.class);
            conditions.and().is("goodsCode",goodsCode);

            try {
                return dao.get(conditions);
            } catch (SQLException e) {
                log.error(e.getMessage(),e);
            }
        }
        return null;
    }

    /**
     * 审核请求
     * @param apply
     * @return
     */
    public CloudGoodsAuditApply auditApply(CloudGoodsAuditApply apply, List<CloudGoodsSpaceAuditItem> spaceAuditItemList){
        List<CloudGoodsAuditApply> auditApplyList = findAuditGoodsRecordBySupplierIdAndGoodsId(apply.getSupplierId(),apply.getGoodsId());
        if(auditApplyList != null && auditApplyList.size() > 0) {
            for (CloudGoodsAuditApply item : auditApplyList) {
                if (EGoodsAuditState.WaitAudit.index().equals(item.getAuditState())) {
                    return item;
                } else if (EGoodsAuditState.Success.index().equals(item.getAuditState())) {
                    return item;
                }
            }
        }
        apply.setAuditState(EGoodsAuditState.WaitAudit.index());
        apply.setCreateDate(new Date());

        JdbcSession.begin();
        try {
            if(dao.insert(apply) > 0){
                if(spaceAuditItemList != null && spaceAuditItemList.size() > 0) {
                    if(CloudGoodsSpaceAuditItemService.self().add(apply.getId(), spaceAuditItemList)) {
                        JdbcSession.commit();
                        return apply;
                    }
                }else{
                    JdbcSession.commit();
                    return apply;
                }
            }
        } catch (SQLException e) {
            log.error(e.getMessage(),e);
        } finally {
            JdbcSession.end();
        }
        return null;
    }

    public boolean toAudit(Long id,Integer auditState,String auditNote)throws LogicException {
        if(id != null && auditState != null) {
            boolean flag = false;
            CloudGoodsAuditApply applyEntity = null;
            JdbcSession.begin();
            try {
                applyEntity = dao.getById(id);
                if (applyEntity == null) {
                    throw new LogicException("云商品发布申请不存在");
                }

                if (EGoodsAuditState.WaitAudit.index().equals(applyEntity.getAuditState())) {
                    Conditions condition = new Conditions(CloudGoodsAuditApply.class);
                    condition.and().is("id", id);
                    condition.and().is("auditState", EGoodsAuditState.WaitAudit.index());

                    CloudGoodsAuditApply updateEntity = new CloudGoodsAuditApply();
                    updateEntity.setAuditNote(auditNote);
                    updateEntity.setAuditState(auditState);

                    if (EGoodsAuditState.Success.index().equals(auditState)) {
                        List<CloudGoodsSpaceAuditItem> spaceAuditItemList = CloudGoodsSpaceAuditItemService.self().findByApplyId(applyEntity.getId());
                        CloudGoods goods = CloudGoodsService.self().save(applyEntity, spaceAuditItemList);   //生成云商品
                        if (goods != null) {
                            updateEntity.setGoodsCode(goods.getId());
                            if (dao.updateNotNull(updateEntity, condition) > 0) {
                                applyEntity.setGoodsCode(goods.getId());
                                JdbcSession.commit();
                                flag = true;
                            }
                        }
                    } else {
                        if (dao.updateNotNull(updateEntity, condition) > 0) {
                            JdbcSession.commit();
                            flag = true;
                        }
                    }
                } else {
                    if (auditState.equals(applyEntity.getAuditState())) {
                        flag = true;
                    } else {
                        throw new LogicException("云商品发布申请已审核");
                    }
                }
            } catch (SQLException e) {
                log.error(e.getMessage(), e);
            } finally {
                JdbcSession.end();
            }

            if (flag) {
                GoodsAuditResultNotice.Body notice = new GoodsAuditResultNotice.Body();
                notice.setGoodsId(applyEntity.getGoodsId());
                notice.setAuditId(applyEntity.getId());
                notice.setAuditState(auditState);
                notice.setGoodsCode(applyEntity.getGoodsCode());
                notice.setAuditNote(applyEntity.getAuditNote());

                GoodsAuditResultNotice apiReq = new GoodsAuditResultNotice();
                apiReq.setBody(notice);

                DefaultAPIResponse apiResp = SupplyChainNoticeService.self().goodsAuditResultNotice(applyEntity.getSupplierId(),apiReq);
                if (apiResp == null) {
                    log.error("向{{0}}供货商发送{{1}}商品审核结果失败，无结果返回", applyEntity.getSupplierId(), applyEntity.getGoodsId());
                } else if (!DefaultAPICodeConstants.SUCCESS.equals(apiResp.getCode())) {
                    log.error("向{{0}}供货商发送{{1}}商品审核结果失败，失败信息：{{0}}", applyEntity.getSupplierId(), applyEntity.getGoodsId(), apiResp.getMsg());
                }
                return true;
            }
        }
        return false;
    }

    public boolean closeAuditByGoodsCode(String goodsCode) throws LogicException {
        CloudGoodsAuditApply auditApply = getByIdGoodsCode(goodsCode);
        if(auditApply == null){
            throw new LogicException("未找到商品审核信息");
        }

        CloudGoodsAuditApply updateEntity = new CloudGoodsAuditApply();
        updateEntity.setId(auditApply.getId());
        updateEntity.setAuditState(EGoodsAuditState.Close.index());

        try {
            return dao.updateNotNull(updateEntity) > 0;
        } catch (SQLException e) {
            log.error(e.getMessage(),e);
        }
        return false;
    }

    public boolean closeAuditById(CloudGoodsAuditApply apply) throws LogicException {
        boolean flag = true;
        if(EGoodsAuditState.Close.index().equals(apply.getAuditState())){
            return true;
        }
        if(EGoodsAuditState.Success.index().equals(apply.getAuditState())){
            CloudGoods goods = CloudGoodsService.self().getById(apply.getGoodsCode());
            if(goods != null){
                flag = CloudGoodsService.self().logicDelete(goods);
            }else{
                log.error("关闭审核时，未找到云商品信息，云商品ID：{{0}}",apply.getGoodsCode());
            }
        }
        if(flag) {
            Conditions conditions = new Conditions(CloudGoodsAuditApply.class);
            conditions.and().is("id", apply.getId());
            conditions.and().is("auditState", apply.getAuditState());

            CloudGoodsAuditApply updateEntity = new CloudGoodsAuditApply();
            updateEntity.setAuditState(EGoodsAuditState.Close.index());
            updateEntity.setAuditNote("供应链端请求关闭");
            try {
                return dao.updateNotNull(updateEntity, conditions) > 0;
            } catch (SQLException e) {
                log.error(e.getMessage(), e);
            }
        }
        return false;
    }

    public boolean deleteById(Long id) throws LogicException {
        if (id != null){
            CloudGoodsAuditApply auditApply = getById(id);
            if(auditApply == null){
                throw new LogicException("未找到商品审核信息");
            }
            JdbcSession.begin();
            try {
               if(dao.deleteById(id) > 0){
                   if(CloudGoodsSpaceAuditItemService.self().deleteByApplyId(id)){
                       if(EGoodsAuditState.Success.index().equals(auditApply.getAuditState())
                            || EGoodsAuditState.Close.index().equals(auditApply.getAuditState())){
                            CloudGoods goods = CloudGoodsService.self().getById(auditApply.getGoodsCode());
                            if(goods != null) {
                                if (CloudGoodsService.self().deleteById(goods.getId())) {
                                    JdbcSession.commit();
                                    return true;
                                }
                            }else{
                                JdbcSession.commit();
                                return true;
                            }
                       }else {
                           JdbcSession.commit();
                           return true;
                       }
                   }
               }
            } catch (SQLException e) {
                log.error(e.getMessage(),e);
            }finally {
                JdbcSession.end();
            }
        }
        return false;
    }

}
